package com.zmm.weblog.jwt.handler;

import com.zmm.weblog.common.utils.Response;
import com.zmm.weblog.jwt.utils.JwtTokenHelper;
import com.zmm.weblog.jwt.utils.ResultUtil;
import com.zmm.weblog.jwt.model.LoginRspVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author:福禄寿
 * @Date:2024/4/27 下午10:43
 * @Des:weblog-springboot
 **/
@Component
@Slf4j
public class RestAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtTokenHelper jwtTokenHelper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //从authentication中获取用户信息,这里时获取用户的用户名
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();

        //生成token
        String username = userDetails.getUsername();
        String token = jwtTokenHelper.generateToken(username);

        //返回token
        LoginRspVo loginRspVo = LoginRspVo.builder().token(token).build();

        ResultUtil.ok(response, Response.success(loginRspVo));
    }
}
